<?php

namespace app\common\model;

use think\Model;

class AuthRule extends Model {

    /**
     * 定义主键
     * @var string
     */
    protected $pk = 'ar_id';

    /**
     * @desc 递归菜单查询
     * @rule 数据为父子级children树形结构
     * @param int $parentId 父级ID
     * @param int $level 数据层级
     * @return array
     */
    public function getChildrenTree($parentId = 0, $level = 0) {
        $field = [
            'ar_id as id',
            'ar_name as name',
            'ar_parent_id as parentId',
            'ar_controller_action as controllerAction',
            'ar_sort as sort',
            'ar_icon as icon',
            'ar_status as status',
            'ar_modify_time as modifyTime',
            'ar_create_time as createTime',
        ];
        $data = $this->field($field)
            ->where(['ar_parent_id' => $parentId])
            ->order('ar_sort', 'desc')
            ->select();
        if($data){
            foreach ($data as $k => $v) {
                $v['level'] = $level;
                if($v['parentId'] == $parentId) {
                    $data[$k]['children'] = $this->getChildrenTree($v['id'], $level+1) ?: [];
                }
            }
        }
        return $data;
    }

    /**
     * @desc 递归菜单查询
     * @rule 同级树形结构
     * @param int $parentId 父级ID
     * @param int $level 数据层级
     * @return array
     */
    public function getTree($parentId = 0, $level = 0) {
        static $result = [];
        $field = [
            'ar_id as id',
            'ar_name as name',
            'ar_parent_id as parentId',
            'ar_controller_action as controllerAction',
            'ar_sort as sort',
            'ar_icon as icon',
            'ar_status as status',
            'ar_modify_time as modifyTime',
            'ar_create_time as createTime',
        ];
        $data = $this->field($field)
            ->where(['ar_parent_id' => $parentId])
            ->order('ar_sort', 'desc')
            ->select();

        if($data) {
            foreach ($data as $k => $v) {
                $v['level'] = $level;
                if($v['parentId'] == $parentId) {
                    $result[] = $v;
                    $this->getTree($v['id'], $level+1);
                }
            }
        }
        return $result;
    }

    /**
     * @desc 将有权限的菜单组成children树形结构
     * @param $data
     * @param int $parent_id
     * @return array
     */
    public function getAuthChildren($data, $parent_id = 0){
        $return = [];
        if($data){
            foreach($data as $k => $v){
                if($v['parentId'] == $parent_id) {
                    $children = $this->getAuthChildren($data, $v['id']);
                    $children ? $v['children'] = $children : null;
                    $return[] = $v;
                }
            }
        }
        return $return;
    }
}